package demo.huodongbaoming.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 端口显示控制器
 * 用于展示当前服务实例的端口号，验证负载均衡效果
 */
@RestController
@RequestMapping("/api/instance")
public class PortDisplayController {

    @Value("${server.port}")
    private int serverPort;
    
    @Value("${spring.application.name}")
    private String applicationName;
    
    @Autowired
    private Environment environment;
    
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    /**
     * 获取当前服务实例信息
     * @return 包含端口号的实例信息
     */
    @GetMapping("/info")
    public Map<String, Object> getInstanceInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("service", applicationName);
        info.put("port", serverPort);
        info.put("activeProfiles", environment.getActiveProfiles());
        info.put("defaultProfile", environment.getDefaultProfiles());
        info.put("timestamp", System.currentTimeMillis());
        info.put("datetime", LocalDateTime.now().format(formatter));
        info.put("message", "这是运行在端口 " + serverPort + " 的服务实例（配置文件: " + getCurrentProfile() + "）");
        
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            info.put("hostname", localHost.getHostName());
            info.put("ip", localHost.getHostAddress());
        } catch (UnknownHostException e) {
            info.put("error", "无法获取主机信息: " + e.getMessage());
        }
        
        // 添加一些系统信息
        info.put("javaVersion", System.getProperty("java.version"));
        info.put("osName", System.getProperty("os.name"));
        info.put("osVersion", System.getProperty("os.version"));
        
        return info;
    }
    
    /**
     * 简单的健康检查端点
     * @return 健康状态
     */
    @GetMapping("/health")
    public Map<String, Object> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("port", serverPort);
        health.put("activeProfiles", environment.getActiveProfiles());
        health.put("timestamp", System.currentTimeMillis());
        health.put("datetime", LocalDateTime.now().format(formatter));
        return health;
    }
    
    /**
     * 返回简单的文本信息，方便直观观察负载均衡效果
     * @return 文本信息
     */
    @GetMapping("/text")
    public String getInstanceText() {
        return "当前请求来自端口: " + serverPort;
    }
    
    /**
     * 获取当前使用的配置文件
     * @return 配置文件名称
     */
    private String getCurrentProfile() {
        String[] activeProfiles = environment.getActiveProfiles();
        if (activeProfiles.length > 0) {
            return String.join(",", activeProfiles);
        } else {
            return "default";
        }
    }
} 